package com.demo.common.handler;


import com.demo.common.Result;
import com.demo.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.resource.NoResourceFoundException;

/**
 * Author：潘建冰
 * Package：com.electrotoolmanager.exception
 * Project：ElectroToolManager
 * name：BusinessException
 * Date：2025/3/24  21:09
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler(BusinessException.class)
    public Result<Void> handleBusinessException(BusinessException e) {
        log.error("业务异常: {}", e.getMessage());
        return Result.error(e.getMessage());

    }


    /**
     * 参数校验异常（@Valid、@Validated）
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Void> handleValidationException(MethodArgumentNotValidException e) {
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        log.error("参数校验失败: {}", message, e);
        return Result.error(message);
    }

    /**
     * JSON 解析异常 / 请求体格式错误
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Result<Void> handleHttpMessageNotReadable(HttpMessageNotReadableException e) {
        log.error("请求体解析异常: {}", e.getMessage(), e);
        Throwable cause = e.getCause();
        if (cause instanceof com.fasterxml.jackson.core.JsonParseException) {
            return Result.error("JSON 格式错误");
        }
        return Result.error("请求参数格式错误");
    }

    /**
     * 缺少请求参数异常（?xxx= 这种）
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public Result<Void> handleMissingParams(MissingServletRequestParameterException e) {
        log.error("缺少必要参数: {}", e.getMessage(), e);
        return Result.error("缺少必要参数: " + e.getParameterName());
    }

    /**
     * 类型转换异常（比如 String 转 Integer 失败）
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public Result<Void> handleTypeMismatch(MethodArgumentTypeMismatchException e) {
        log.error("参数类型转换失败: {}", e.getMessage(), e);
        return Result.error("参数类型错误: " + e.getName());
    }

    /**
     * 静态资源未找到异常
     */
    @ExceptionHandler(NoResourceFoundException.class)
    public Result<Void> handleNoResourceFound(NoResourceFoundException e) {
        log.error("静态资源未找到: {}", e.getMessage(), e);
        return Result.error("请求的资源不存在，请检查API路径是否正确");
    }

    @ExceptionHandler(Exception.class)
    public Result<Void> handleException(Exception e) {
        log.error("系统异常: "+ e.getMessage(),e);
        return Result.error("系统异常，请联系管理员");
    }
}
